import { get } from '../js/api.js';

async function searchScore() {
    const sid = document.getElementById('sid').value.trim();
    if (!sid) {
        alert("请输入学号！");
        return;
    }
    try {
        // 从后端获取学生成绩数据
        const scoreResponse = await get(`/scores?sid=${sid}`);
        
        // 从后端获取学生信息数据
        const userResponse = await get(`/users/${sid}`);
        
        if (scoreResponse.status === 'success') {
            const scoreData = scoreResponse.data;
            console.log("成绩数据:",userResponse);
            
            // 更新学生信息
            if (userResponse.success === true && userResponse.data) {
                const userData = userResponse.data;
                document.getElementById('name').textContent = userData.name || '未知';
                document.getElementById('credits').textContent = userData.credits || 0;
                // 处理学生照片
                const photoElement = document.querySelector('.student-info img');
                if (userData.photo) {
                    let photoData = userData.photo.trim();
                    
                    // 解决JSON转义问题：将反斜杠转义的字符还原
                    photoData = photoData.replace(/\\u([0-9a-fA-F]{4})/g, function(match, p1) {
                        return String.fromCharCode(parseInt(p1, 16));
                    });

                    // 确保是完整的 data URL
                    if (!photoData.startsWith('data:image')) {
                        // 如果缺少前缀，自动添加（假设为 PNG 格式）
                        photoData = `data:image/png;base64,${photoData}`;
                    }
                    
                    photoElement.src = photoData;
                } else {
                    photoElement.src = '../images/默认头像34.png';
                }
            } else {
                // 如果无法获取用户信息，使用成绩数据中的信息
                document.getElementById('name').textContent = scoreData.scores.length > 0 ? scoreData.scores[0].student_name : '未知';
                
                // 计算总学分
                let totalCredits = 0;
                scoreData.scores.forEach(item => {
                    totalCredits += parseFloat(item.credits) || 0;
                });
                document.getElementById('credits').textContent = totalCredits;

                // 设置默认照片
                const photoElement = document.querySelector('.student-info img');
                photoElement.src = '../images/默认头像.png';
            }
            
            // 清空表格
            const tbody = document.querySelector('#score-table tbody');
            tbody.innerHTML = '';
            
            // 填充成绩数据
            if (scoreData.scores.length > 0) {
                scoreData.scores.forEach(item => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${item.cid}</td>
                        <td>${item.course_name}</td>
                        <td>${item.score}</td>
                    `;
                    tbody.appendChild(row);
                });
            } else {
                // 如果没有成绩数据，显示提示信息
                const row = document.createElement('tr');
                row.innerHTML = `<td colspan="3" style="text-align: center;">无成绩数据</td>`;
                tbody.appendChild(row);
            }
        } else {
            alert("查询失败: " + scoreResponse.message);
        }
    } catch (error) {
        console.error('查询出错:', error);
        alert("查询出错: " + error.message);
    }
}

// 页面加载完成后绑定事件
document.addEventListener('DOMContentLoaded', () => {
    const searchButton = document.querySelector('.search-box button');
    if (searchButton) {
        searchButton.addEventListener('click', searchScore);
    }

    // 为学号输入框添加回车键支持
    const sidInput = document.getElementById('sid');
    if (sidInput) {
        sidInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                searchScore();
            }
        });
    }
});

export { searchScore };